<?php
// 后台用户模块
class UserAction extends CommonAction
{
    function _filter(&$map)
    {
        $map['id'] = array('egt', 2);
        $map['account'] = array('like', "%" . $_POST['account'] . "%");
        $map['nickname'] = array('like', "%" . $_POST['nickname'] . "%");
        $map['mobilenum'] = array('like', "%" . $_POST['mobilenum'] . "%");
    }

    // 检查帐号
    public function checkAccount()
    {
        if (!preg_match('/^[a-z]\w{4,}$/i', $_POST['account'])) {
            $this->error('用户名必须是字母+数字，且5位以上！');
        }
        $User = M("User");
        // 检测用户名是否冲突
        $name = $_REQUEST['account'];
        $result = $User->getByAccount($name);
        if ($result) {
            $this->error('该用户名已经存在！');
        } else {
            $this->success('该用户名可以使用！');
        }
    }

    // 插入数据
//	public function insert() {
//		// 创建数据对象
//		$User	 =	 D("User");
//		if(!$User->create()) {
//			$this->error($User->getError());
//		}else{
//			// 写入帐号数据
//			if($result	 =	 $User->add()) {
//				$this->addRole($result);
//				$this->success('用户添加成功！');
//			}else{
//				$this->error('用户添加失败！');
//			}
//		}
//	}

    protected function addRole($userId, $roleid)
    {
        $RoleUser = M("role_user");
        $RoleUser->user_id = $userId;
        $RoleUser->role_id = $roleid;
        $RoleUser->add();
    }


    function insert()
    {
        //B('FilterString');
        $name = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        $list = $model->add();
        if ($list !== false) { //保存成功
            $this->addRole($list, $_POST["role_id"]);
            $this->assign('jumpUrl', Cookie::get('_currentUrl_'));
            $this->success('新增用户成功!');
        } else {
            //失败提示
            $this->error('新增用户失败!');
        }
    }

    public function index()
    {
        //列表过滤器，生成查询Map对象
        $map = $this->_search();
        if (method_exists($this, '_filter')) {
            $this->_filter($map);
        }
        if ($_SESSION['city'] > 100) {
            $map[city] = $_SESSION['city'];
        }
        $name = $this->getActionName();
        $model = D($name);
        if (!empty ($model)) {
            $this->_list($model, $map);
        }
        $this->display();
        return;
    }

    protected function _list($model, $map, $sortBy = '', $asc = false, $countPk = 'id')
    {
        //排序字段 默认为主键名
        if (!empty ($_REQUEST ['_order'])) {
            $order = $_REQUEST ['_order'];
        } else {
            $order = !empty ($sortBy) ? $sortBy : $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if (isset ($_REQUEST ['_sort'])) {
//			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
            $sort = $_REQUEST ['_sort'] == 'asc' ? 'asc' : 'desc'; //zhanghuihua@msn.com
        } else {
            $sort = $asc ? 'asc' : 'desc';
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count($countPk);
        if ($count > 0) {
            import("@.ORG.Util.Page");
            //创建分页对象
            if (!empty ($_REQUEST ['listRows'])) {
                $listRows = $_REQUEST ['listRows'];
            } else {
                $listRows = '';
            }
            $p = new Page ($count, $listRows);
            //分页查询数据
            $voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();

            //echo $model->getlastsql();
            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();
            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式

            $role_user = M(role_user);
            $jiaose = $role_user->select();
            foreach (array_column($voList, 'id') as $key => $val) {
                $voList[$key]['jiaose'] = '0';
                foreach (array_column($jiaose, 'user_id') as $key2 => $val2) {
                    if ($val == $val2) {
                        $voList[$key]['jiaose'] = $jiaose[$key2]['role_id'];
                    }
                }

            }
            $jiaose_list = C(JIAOSE);
            $city_list = C(CITY);
            $this->assign('jiaose_list', $jiaose_list);
            $this->assign('city_list', $city_list);

            //模板赋值显示
            $this->assign('list', $voList);
            $this->assign('sort', $sort);
            $this->assign('order', $order);
            $this->assign('sortImg', $sortImg);
            $this->assign('sortType', $sortAlt);
            $this->assign("page", $page);
        }
        $this->assign('totalCount', $count);
        $this->assign('numPerPage', $p->listRows);
        $this->assign('currentPage', !empty($_REQUEST[C('VAR_PAGE')]) ? $_REQUEST[C('VAR_PAGE')] : 1);

        Cookie::set('_currentUrl_', __SELF__);
        return;
    }

    //重置密码
    public function resetPwd()
    {
        $id = $_POST['id'];
        $password = $_POST['password'];
        if ('' == trim($password)) {
            $this->error('密码不能为空！');
        }
        $User = M('User');
        $User->password = md5($password);
        $User->id = $id;
        $result = $User->save();
        if (false !== $result) {
            $this->success("密码修改为$password");
        } else {
            $this->error('重置密码失败！');
        }
    }

    function userforeverdelete()
    {
        $name = $this->getActionName();
        $model = D($name);
        if (!empty ($model)) {
            $pk = $model->getPk();
            $id = $_REQUEST [$pk];
            if (isset ($id)) {
                if ($model->hasRole($id)) {
                    $model->delRole($id);
                }

                $condition = array($pk => array('in', explode(',', $id)));
                if (false !== $model->where($condition)->delete()) {
                    //echo $model->getlastsql();
                    $this->success('删除成功！');
                } else {
                    $this->error('删除失败！');
                }
            } else {
                $this->error('非法操作');
            }
        }
        $this->forward();
    }

    public function _before_add()
    {
        $list = C(CITY);
        $city_list = array();
        if ($_SESSION['city'] > 34) {
            foreach ($list as $key => $val) {
                if ($key == $_SESSION['city']) {
                    $city_list[$key] = $val;
                }

            }

        } else {
            foreach ($list as $key => $val) {
                if ($key > 34) {
                    $city_list[$key] = $val;
                }

            }
        }

        $this->assign('city_list', $city_list);

    }

    public function _before_edit()
    {
        $city_list = C(CITY);
        $this->assign('city_list', $city_list);
        if ($_SESSION['role_id'] == 3) {
            $userdedit = 'readonly="readonly"';
        } else {
            $userdedit = 'class="required" name="account"';
        }

        $this->assign('userdedit', $userdedit);
    }
}
?>